<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <main class="aui-content">
        <div class="login-header">
          <h2 class="login-brand">{{ $t('brand.lg') }}</h2>
        </div>
        <div class="login-body">
          <el-tabs v-model="activeName" v-if="!dataForm.code">
            <el-tab-pane label="通过手机号找回" name="sms">
              <el-form :model="mobileForm" :rules="mobileRule" ref="mobileForm" status-icon>
                <el-form-item>
                  <el-select v-model="$i18n.locale" class="w-percent-100">
                    <el-option v-for="(val, key) in i18nMessages" :key="key" :label="val._lang" :value="key">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="mobile">
                  <el-input v-model="mobileForm.mobile" :placeholder="$t('login.mobile')">
                    <i slot="prefix" class="el-input__icon el-icon-phone-outline"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="code">
                  <el-col :span="10">
                    <el-input v-model="mobileForm.code" :placeholder="$t('login.validateCode')">
                      <span slot="prefix" class="el-input__icon">
                        <svg class="icon-svg" aria-hidden="true">
                          <use xlink:href="#icon-lock"></use>
                        </svg>
                      </span>
                    </el-input>
                  </el-col>
                  <el-col :span="7" :offset="7">
                    <el-button @click="getMobileCode()" :disabled="mobileFlag" class="w-percent-100" :loading="loading">
                      {{ mobileBtnTitle }}
                    </el-button>
                  </el-col>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="mobileFormSubmitHandle()" class="w-percent-100" :loading="loading">
                    下一步
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="通过邮箱找回" name="email">
              <el-form :model="emailForm" :rules="emailRule" ref="emailForm" status-icon>
                <el-form-item>
                  <el-select v-model="$i18n.locale" class="w-percent-100">
                    <el-option v-for="(val, key) in i18nMessages" :key="key" :label="val._lang" :value="key">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="email">
                  <el-input v-model="emailForm.email" :placeholder="$t('login.email')">
                    <i slot="prefix" class="el-input__icon el-icon-user"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="code">
                  <el-col :span="10">
                    <el-input v-model="emailForm.code" :placeholder="$t('login.validateCode')">
                      <span slot="prefix" class="el-input__icon">
                        <svg class="icon-svg" aria-hidden="true">
                          <use xlink:href="#icon-lock"></use>
                        </svg>
                      </span>
                    </el-input>
                  </el-col>
                  <el-col :span="7" :offset="7">
                    <el-button @click="getEmailCode()" :disabled="emailFlag" class="w-percent-100" :loading="loading">
                      {{ emailBtnTitle }}
                    </el-button>
                  </el-col>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="emailFormSubmitHandle()" class="w-percent-100" :loading="loading">
                    下一步
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-row>
              <el-link :underline="false" @click="gotoLoginView()">返回登录</el-link>
            </el-row>
          </el-tabs>
          <div v-else>
            <el-form :model="dataForm" :rules="dataRule" ref="passwordForm">
              <el-form-item prop="newPassword" :label="$t('updatePassword.newPassword')"
                :show-message="!valid_password">
                <el-input v-model="dataForm.newPassword" type="password" @input="p_len"
                  :placeholder="$t('updatePassword.newPassword')"></el-input>
                <span
                  v-bind:class="{ show_password_length: typed, pwd_level1:pwdLevel===1, pwd_level2:pwdLevel===2, pwd_level3:pwdLevel===3, pwd_level4:pwdLevel===4}"
                  class="password_length">{{pwdLevel===1?$t('updatePassword.pwdLevel1'):pwdLevel===2?$t('updatePassword.pwdLevel2'):pwdLevel===3?$t('updatePassword.pwdLevel3'):$t('updatePassword.pwdLevel4')}}</span>
                <div class="lnu_container">
                  <p v-bind:class="{ number_valid: contains_number }">{{$t('updatePassword.number')}}</p>
                  <p v-bind:class="{ lovercase_valid: contains_lovercase }">{{$t('updatePassword.lovercase')}}</p>
                  <p v-bind:class="{ uppercase_valid: contains_uppercase }">{{$t('updatePassword.uppercase')}}</p>
                  <p v-bind:class="{ special_valid: contains_special }">{{$t('updatePassword.special')}}</p>
                </div>
              </el-form-item>
              <el-form-item prop="comfirmPassword" :label="$t('updatePassword.comfirmPassword')">
                <el-input v-model="dataForm.comfirmPassword" type="password"
                  :placeholder="$t('updatePassword.comfirmPassword')"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="passwordFormSubmitHandle()" class="w-percent-100" :loading="loading">
                  修改修改
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="login-footer">
          <p>
            <a href="http://www.uniedp.cn/#/login" target="_blank">{{ $t('login.demo') }}</a>
          </p>
          <p><a href="http://www.uniedp.cn" target="_blank">{{ $t('login.copyright') }}</a>2019 © uniedp.cn</p>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { messages } from '@/i18n'
import {
  validateMobile,
  validateEmail
} from '@/utils/validate'
import password from '@/mixins/view-password'

export default {
  mixins: [password],
  data () {
    return {
      activeName: 'sms',
      count: 60,
      timer: null,
      mobileFlag: false,
      emailFlag: false,
      mobileBtnTitle: this.$t('login.checkCodeBtn'),
      emailBtnTitle: this.$t('login.checkCodeBtn'),
      loading: false,
      i18nMessages: messages,
      captchaPath: '',
      // dataForm: {
      //   username: '',
      //   password: '',
      //   uuid: '',
      //   captcha: ''
      // },
      mobileForm: {
        mobile: '',
        code: null
      },
      emailForm: {
        email: '',
        code: null
      },
      dataForm: {
        password: '',
        newPassword: '',
        comfirmPassword: '',
        code: '',
        email: '',
        mobile: ''
      },
      isValidateCodeLogin: false
    }
  },
  computed: {
    mobileRule () {
      return {
        mobile: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    },
    emailRule () {
      return {
        email: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {

  },
  methods: {
    gotoLoginView () {
      this.$router.push({ path: '/login' })
    },
    // 获取手机验证码
    getMobileCode () {
      this.$refs.mobileForm.validateField('mobile', mobileError => {
        if (!mobileError) {
          const TIME_COUNT = 120
          // 发送手机验证码
          if (!this.timer) {
            this.count = TIME_COUNT
            this.mobileFlag = true
            // 验证手机号码是否正确
            this.sendSmsCode(this.mobileForm.mobile)
            this.mobileBtnTitle = '重新发送（' + this.count + '）'
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
                this.mobileBtnTitle = '重新发送（' + this.count + '）'
              } else {
                this.mobileFlag = false
                clearInterval(this.timer)
                this.timer = null
                this.mobileBtnTitle = '重新发送'
              }
            }, 1000)
          }
        } else {
          return false
        }
      })
    },
    // 获取邮箱验证码
    getEmailCode () {
      this.$refs.emailForm.validateField('email', mobileError => {
        if (!mobileError) {
          const TIME_COUNT = 120
          // 发送手机验证码
          if (!this.timer) {
            this.count = TIME_COUNT
            this.emailFlag = true
            // 验证手机号码是否正确
            this.sendEmailCode(this.emailForm.email)
            this.emailBtnTitle = '重新发送（' + this.count + '）'
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
                this.emailBtnTitle = '重新发送（' + this.count + '）'
              } else {
                this.emailFlag = false
                clearInterval(this.timer)
                this.timer = null
                this.emailBtnTitle = '重新发送'
              }
            }, 1000)
          }
        } else {
          return false
        }
      })
    },
    // 发送短信验证码
    sendSmsCode (loginKey) {
      this.$http.post(`/resetPassword/sendSmsCode`, { params: { mobile: loginKey } }).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
      })
    },
    // 发送邮件验证码
    sendEmailCode (loginKey) {
      this.$http.post(`/resetPassword/sendEmailCode`, { params: { mobile: loginKey } }).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
      })
    },
    // 手机验证码提交
    mobileFormSubmitHandle: debounce(function () {
      this.loading = true
      this.$refs.mobileForm.validate((valid) => {
        if (!valid) {
          this.loading = false
          return false
        }
        this.$http.post('/resetPassword/verification/mobile', this.mobileForm).then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return false
          }
          this.dataForm.mobile = this.mobileForm.mobile
          this.dataForm.code = res.data
        }).catch((err) => {
          this.loading = false
          console.error(err)
          this.$message.error('系统异常，请联系管理员')
        })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 邮箱验证码提交
    emailFormSubmitHandle: debounce(function () {
      this.loading = true
      this.$refs.emailForm.validate((valid) => {
        if (!valid) {
          this.loading = false
          return false
        }
        this.postLoginValidateCode(this.emailForm)
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 提交注册
    passwordFormSubmitHandle: debounce(function () {
      this.loading = true
      this.$refs.passwordForm.validate((valid) => {
        if (!valid) {
          this.loading = false
          return false
        }
        console.log(this.dataForm)
        this.dataForm.password = this.dataForm.newPassword
        let url = '/resetPassword/mobile'
        if (this.dataForm.email) {
          url = '/resetPassword/email'
        }
        this.$http.post(url, this.dataForm).then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return false
          }
          this.$message.error('修改成功')
          this.gotoLoginView()
        }).catch((err) => {
          this.loading = false
          console.error(err)
          this.$message.error('系统异常，请联系管理员')
        })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style scoped>
.password_length {
  padding: 2px 10px;
  line-height: 20px;
  position: absolute;
  top: 48%;
  right: 10px;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
  background: #fbd490;
  color: rgba(71, 87, 98, 0.8);
  border-radius: 4px;
  font-size: 13px;
  display: none;
  -webkit-transition: all 0.1s;
  transition: all 0.1s;
}

.valid_password_length {
  background: #00ad7c;
  color: rgba(255, 255, 255, 0.9);
}

.pwd_level1,
.pwd_level2 {
  background: #f56c6c;
  color: rgba(255, 255, 255, 0.9);
}

.pwd_level3 {
  background: #e6a23c;
  color: rgba(255, 255, 255, 0.9);
}

.pwd_level4 {
  background: #5cb85c;
  color: rgba(255, 255, 255, 0.9);
}

.show_password_length {
  display: block;
}

.lnu_container {
  width: 420px;
  height: auto;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.lnu_container p {
  width: 100px;
  height: auto;
  font-size: 12px;
  line-height: 1.2;
  text-align: center;
  border-radius: 2px;
  color: rgba(71, 87, 98, 0.8);
  background: -webkit-linear-gradient(left, #00ad7c 50%, #eee 50%);
  background: linear-gradient(to right, #00ad7c 50%, #eee 50%);
  background-size: 201% 100%;
  background-position: right;
  -webkit-transition: background 0.3s;
  transition: background 0.3s;
}

.lovercase_valid,
.number_valid,
.uppercase_valid,
.special_valid {
  background-position: left !important;
  color: rgba(255, 255, 255, 0.9) !important;
}

.valid_password_container {
  display: block;
  margin: 10px auto;
  border-radius: 4px;
  position: relative;
  background: #00ad7c;
  width: 20px;
  height: 20px;
  visibility: hidden;
  opacity: 0;
}
</style>
